<?php

/*

___Canvas Core Functions________________________________________

Core functions for generating the Canvas GUI
and manipulating layout contents.

________________________________________________________________

*/

require_once('canvas-includes.php');

function canvas_add_plugin($path) {
	global $canvas_external_plugins;
	if(substr($path, -3) == 'php') $path = preg_replace('/php$/', 'canvas', $path);
	if(substr($path, -6) == 'canvas' && file_exists($path)) $canvas_external_plugins[] = $path;
}

function canvas_build_canvas() {
	if(isset($_GET["template"])) $template = ABSPATH.'wp-content/themes/'.$_GET["template"];
		else $template = TEMPLATEPATH;
 	if(file_exists($template . "/canvas.php")) {
			if(get_option('canvas_auto_publish') != 'true') echo '<div id="publish"><a href="javascript:void(0)"><img src="'.CANVASURI.'images/publish.gif" title="Publish Your Changes" alt="Publish Changes" id="publish_image" /></a></div>';
				else echo '<div id="publish" class="publish_nobutton"></div>';
			include($template . "/canvas.php");
			echo '<p style="clear: left;"><a href="'.CANVASURI.'canvas-import_functions.php?canvas_import_form=true" class="lbOn"><img src="'.CANVASURI.'images/import.gif" alt="import" title="Import from XML" id="import_image" /></a>'."\n";
			echo '<a href="'.CANVASURI.'canvas-export_functions.php?canvas_export_form=true" class="lbOn"><img src="'.CANVASURI.'images/export.gif" alt="export" title="Export as XML" id="export_image" /></a>'."\n";
			echo '<a href="'.CANVASURI.'canvas-import_functions.php?canvas_restore_form=true&xml_path='.get_template_directory().'/canvas.xml" class="lbOn"><img src="'.CANVASURI.'images/restore.gif" alt="restore" title="Restore from XML" id="restore_image" /></a></p>'."\n";
		} else { canvas_no_theme(); }
}

function canvas_check_theme() {
	global $wpdb, $canvas;
	if(!$wpdb->get_results("SELECT block_id FROM ".$canvas->main." WHERE theme = '".get_option('template')."'")) canvas_install();
		else return;
	$filename = get_template_directory().'/canvas.php';
	if(file_exists($filename)) {
		if(!get_option('canvas_first_install')) update_option('canvas_first_install', time());
		$file_data = implode('', file($filename));
		if(preg_match("|Ink Elements:(.*)|i", $file_data, $ink_string)) $ink_string = trim($ink_string[1]);
		if($wpdb->get_results("SELECT block_id FROM ".$canvas->main." WHERE theme = '".get_option('template')."'") && !$wpdb->get_results("SELECT block_id FROM ".$canvas->main." WHERE zone != 'shelf' AND theme = '".get_option('template')."'")) {
			$xmlfile = get_template_directory().'/canvas.xml';
			if(file_exists($xmlfile)) canvas_import_layout($xmlfile);
		}
		if(function_exists('ink_elements')) ink_elements($ink_string);
		return true;
	} else {
		return false;
	}
}

function canvas_create_draggable($block_id, $zone, $position, $title, $content, $type, $group) {
	$class = 'container';
	if($type == 'plugin') $class = 'container-plugin';
	$class .= ' '.strtolower($group);
	echo '<div class="'.$class.'" id="canvas_'.$zone.'_'.$position.'_'.$block_id.'" title="'.strip_tags($content).'">'."\n";
    echo '<h6 class="handle"><span>'.$title.'</span></h6>'."\n";
    echo canvas_create_plugin_form($zone, $position, $block_id, $type)."\n";
    echo '<div class="content">'.$content."</div>\n";
 	echo '</div>'."\n";
}

function canvas_create_management_block($block,$style='',$delete_button='true') {
	if($block->uri != '') $link = '<a href="'.$block->uri.'">'.$block->author.'</a>';
		else $link = $block->author;
	if($block->type == 'plugin') $class = ' class="plugin '.strtolower($block->block_group).'"';
		else $class = ' class="'.strtolower($block->block_group).'"';
	echo "\t".'<li id="block_'.$block->block_id.'"'.$class.$style.'>';
	if($delete_button == 'true') echo '<a class="delete_block" id="'.$block->block_id.'" href="javascript:void(0)"><img src="'.CANVASURI.'images/delete.png" alt="Delete" title="Delete block"/></a>';
	echo '<a class="duplicate_block" id="'.$block->block_id.'" href="javascript:void(0)"><img src="'.CANVASURI.'images/duplicate.png" alt="Duplicate" title="Duplicate block"/></a>';
	echo '<a class="block_info" id="'.$block->block_id.'" href="javascript:void(0)"><img src="'.CANVASURI.'images/block_info.png" alt="Info" title="Block information"/></a>';
	echo '<h3><span class="title" id="title_'.$block->block_id.'">'.$block->block_name.'</span> by '.$link.'.</h3><p>'.wptexturize($block->description).'</p>';
	echo '<div class="info" id="info_'.$block->block_id.'" style="display: none;"><div><strong>Block Type:</strong> '.$block->type.'<br/><strong>UBI:</strong> '.$block->ubi.'<br/><strong>Group:</strong> '.$block->block_group.'<br/><strong>Block ID:</strong> '.$block->block_id.'<br/><strong>Path:</strong> '.$block->path.'<br/><strong>Zone:</strong> '.$block->zone.'<br/><strong>Position:</strong> '.$block->position.'<br/><strong>Author URI:</strong> '.$block->uri.'</div></div>';
	echo '</li>'."\n";
}

function canvas_create_plugin_form($zone,$position,$block_id,$block_type) {
	if($block_type == 'plugin')
		echo '<a href="'.CANVASURI.'canvas-plugin_form.php?zone='.$zone.'&position='.$position.'&block_id='.$block_id.'" class="lbOn"><img class="lbLink" src="'.CANVASURI.'images/plugin_options.gif" title="Plugin Options" alt="Plugin Options"/></a>';
}

function canvas_css_based_insert() {
	if(file_exists(get_template_directory().'/canvas.php')) {
		$buffer = ob_get_contents();
		ob_end_clean();
	
		$doc = new domDocument;
		@$doc->loadHTML($buffer);
	
		preg_match_all("/canvas_zone\(([A-Za-z0-9\_\-]*)\)/", $buffer, $zones);
		if(!empty($zones[1])) :
			foreach($zones[1] as $zone) {
				ob_start();
				canvas_zone($zone);
				$value = ob_get_contents();
				ob_end_clean();
				
				if($value != '') {
					$node = canvas_getNodeByAttr('class','canvas_zone('.$zone.')',$doc);
					if($node) {
						if(canvas_zone_handler($zone) == 'append') { 
							$node->appendChild($doc->createElement('canvasnode', $value));
						} elseif(canvas_zone_handler($zone) == 'before') { 
							$oldContentNodes = $node->childNodes;
							$oldContent = $doc->createElement('canvasnode');
							foreach($oldContentNodes as $currentNode) {
								$oldContent->appendChild($currentNode->cloneNode(true));
							}
							$node->nodeValue = $value;
							$node->appendChild($oldContent);
						} elseif(canvas_zone_handler($zone) == 'replace') { 
							$node->nodeValue = $value;
						}
					}
				}
			}
			$buffer = remove_canvas_node_names(htmlspecialchars_decode($doc->saveHTML()));	
		endif;
		
		echo $buffer;
	}
}

function canvas_database_plugin($matches, $type = 'select', $variable_value) {
	global $wpdb, $canvas, $table_prefix;
	$content = '';
	if(!isset($matches[3])) $matches[3] = $matches[2];
	
	if($wpdb->get_var("SHOW TABLES LIKE '".$table_prefix.$matches[1]."'") == $table_prefix.$matches[1]) {
		if($data = $wpdb->get_results("SELECT ".$matches[2].", ".$matches[3]." FROM ".$table_prefix.$matches[1])) {
			foreach($data as $row) {
				if($type == 'select') {
					$content .= '<option value="'.$row->$matches[3].'" ';
					if ($row->$matches[3] == $variable_value) $content .= ' selected="selected" ';
					$content .= '>&nbsp;'.$row->$matches[2]."</option>\n";
				} elseif($type == 'radio') {
					$content .= '<label><input type="radio" value="'.$row->$matches[3].'" ';
					if ($row->$matches[3] == $variable_value) $content .= ' checked="checked" ';
					$content .= '/>&nbsp;'.$row->$matches[2].'</label>';
				}
			}
		}
	}
	
	return $content;
}

function canvas_define_zone($zone_name, $parent='', $styles='') {
	global $zones, $parents;
	if($_GET["template"] != '') $theme = $_GET["template"];
		else $theme = get_option('template');
	$parents[] = $parent;
	$zones[] = $zone_name;
	echo '<div class="canvas_droppable_zone '.$zone_name.'" id="'.$zone_name.'"';
	if($styles != '') echo ' style="'.$styles.'"';
	echo '>'."\n";
	get_canvas_draggables($zone_name, $theme);
	echo '</div>'."\n";
}

function canvas_execute_function($function_name, $block_id) {
	global $wpdb, $canvas;
	if($var_data = $wpdb->get_results("SELECT variable_name, value FROM ".$canvas->variables." WHERE parent = '$block_id'")) {
		$url_string = '';
		$vars = array();
		if (!empty($var_data)) {
		  foreach($var_data as $var) {
			$url_string .= '&'.$var->variable_name.'='.$var->value;
			$vars[str_replace($function_name.'_', '', $var->variable_name)] = $var->value;
		  }
		  $url_string = str_replace($function_name.'_', '', $url_string);
		  $url_string .= '&block_id='.$block_id;
		}
		$url_string = substr($url_string, 1);
		if(is_callable($function_name)) $function_name($url_string, $vars);
	}
}

function canvas_getNodeByAttr($attr, $nodeID, $xmldoc) {
	if ($xmldoc->hasChildNodes()) {
		$children = $xmldoc->childNodes;
		foreach($children as $node) {
			if($node->hasAttributes()) {
				$attributes = $node->attributes;
				foreach ($attributes as $attribute) {
					if(($attribute->name == $attr) && (stripos($attribute->value, $nodeID)) !== false) {
						return $node;
					} else {
						if(canvas_getNodeByAttr($attr,$nodeID,$node))
							return canvas_getNodeByAttr($attr,$nodeID,$node);
					}
				}
			} else {
				if(canvas_getNodeByAttr($attr,$nodeID,$node))
					return canvas_getNodeByAttr($attr,$nodeID,$node);
			}
		}
	} else {
		return null;
	}
}

function canvas_head() {
	global $installed;
	if($_GET["page"] == 'canvas.php') : ?>
<link rel="stylesheet" href="<?php echo CANVASURI; ?>stylesheet.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php echo CANVASURI; ?>lightbox.css" type="text/css" media="screen" />
		<?php if(!isset($_GET["template"])) : ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory') ?>/canvas.css" type="text/css" media="screen" />
		<?php else : ?>
<link rel="stylesheet" href="<?php echo get_bloginfo('wpurl').'/wp-content/themes/'.$_GET["template"]; ?>/canvas.css" type="text/css" media="screen" />
		<?php endif; ?>
<script language="JavaScript" type="text/javascript" src="<?php echo CANVASURI; ?>js/prototype.js"></script>
<script language="JavaScript" type="text/javascript" src="<?php echo CANVASURI; ?>js/scriptaculous.js"></script>
<script language="JavaScript" type="text/javascript" src="<?php echo CANVASURI; ?>js/lightbox.js"></script>
<script language="JavaScript" type="text/javascript" src="<?php echo CANVASURI; ?>js/canvas-ajax.js.php"></script>
	<?php endif;
	if($_GET["content"] == 'manage') : ?>
<script language="JavaScript" type="text/javascript" src="<?php echo CANVASURI; ?>js/canvas-management.js"></script>
	<?php endif;
	if($_GET["content"] == 'options') : ?>
<script language="JavaScript" type="text/javascript" src="<?php echo CANVASURI; ?>js/canvas-options.js"></script>
	<?php endif;
}

function canvas_include_block($filename) {
	include($filename);
}

function canvas_interrupt() {
	if(file_exists(get_template_directory().'/canvas.php'))
		ob_start();
}

function canvas_no_theme() {
	$theme = current_theme_info();
	echo '<div class="wrap"><h2>Theme Not Supported</h2><p>The theme you are currently using ('.$theme->title.' by '.$theme->author.') doesn\'t seem to support Canvas. At this point in the game, Canvas only supports themes that are built to run with the Canvas layout and styling system. To use Canvas, you\'ll have to either <a href="themes.php">select</a> a different theme from your collection or <a href="http://freshpursuits.com/canvas/themes">download</a> a new one.</p>';
	$themes = get_themes();
	$theme_names = array_keys($themes);
	natcasesort($theme_names);
	$canvas_themes = array();
	foreach($theme_names as $index => $theme_name) {
		$stylesheet_dir = $themes[$theme_name]['Stylesheet Dir'];
		if(file_exists(ABSPATH . $stylesheet_dir . '/canvas.php')) {
			$canvas_themes[$index]['title'] = $themes[$theme_name]['Title'];
			$canvas_themes[$index]['template'] = $themes[$theme_name]['Template'];
			$canvas_themes[$index]['directory'] = $stylesheet_dir;
		}
	}
	if(!empty($canvas_themes)) {
		echo '<p>Although your current theme isn\'t compatible, you do have some Canvas compatible themes available. Select a theme from the listing below to edit an inactive theme.</p>'."\n";
		foreach($canvas_themes as $theme) {
			$link = 'themes.php?page=canvas.php&amp;template='.$theme['template'];
			echo '<h3><p><a href="'.$link.'">&raquo; '.$theme['title'].'</a></p></h3>'."\n";
		}
	}
	echo '<p>If you\'ve already downloaded a Canvas-compatible version of this theme, you may want to contact the theme author to resolve the issue.</p><p><strong>Need a good theme?</strong> Check out the official list of <a href="http://outlet.freshpursuits.com/">Canvas-compatible themes</a>.</p>';
	echo '</div>'."\n";
}

function canvas_show_zone_options($zone, $theme) {
	$content_position = canvas_zone_handler($zone);
	
	if(get_option('canvas_hide_zone_options') == 'true') { $display = ' style="display: none;"'; $toggle_style = ' style="background-color: #cfcfcf;"'; }
		else { $display = ''; $toggle_style = ''; }
	$content = '<h8 id="togglezoneoption_'.$zone.'"'.$toggle_style.'></h8>'."\n";
	$content .= '<span class="canvas_zone_options" id="options_'.$zone.'"'.$display.'>'."\n";
	$content .= '<select class="zone_content_options" id="zoneoption_'.$zone.'" name="zoneoption_'.$zone.'">'."\n";
	$content .= '<option value="before">Insert blocks before original content.'."\n";
	$content .= '<option value="append">Insert blocks after original content.'."\n";
	$content .= '<option value="replace">Replace original content.'."\n";
	$content .= '</select>'."\n";
	$content .= '<img src="'.CANVASURI.'images/replace_up.png" title="Replace original content" onclick="Canvas.zoneHandler(\''.$zone.'\', \'replace\')" />';
	$content .= '<img src="'.CANVASURI.'images/append_up.png" title="Insert after original content" onclick="Canvas.zoneHandler(\''.$zone.'\', \'append\')" />';
	$content .= '<img src="'.CANVASURI.'images/before_up.png" title="Insert before original content" onclick="Canvas.zoneHandler(\''.$zone.'\', \'before\')" />';
	$content .= '</span>'."\n";
	if($content_position != '') $content = str_replace($content_position.'_up', $content_position.'_down', $content);
	$content = str_replace('value="'.$content_position.'"', 'value="'.$content_position.'" selected="selected"', $content);

	echo $content;
}

function canvas_zone($zone_name) {
	global $wpdb, $canvas;
	if($zone_data = $wpdb->get_results("SELECT block_id, path, type, position, zone FROM ".$canvas->main." WHERE zone = '$zone_name' AND theme = '".get_option('template')."' ORDER BY position")) {
		foreach($zone_data as $zone) {
			if($zone->type == 'block') {
				canvas_include_block($zone->path);
			} elseif($zone->type == 'plugin') {
				canvas_execute_function($zone->path, $zone->block_id);
			} else {
				echo 'ERROR: Zone type not defined.';
			}
		}
	}
}

function canvas_zone_handler($zone) {
	global $wpdb, $canvas;
	$position = $wpdb->get_var("SELECT value FROM ".$canvas->zone_options." WHERE option_name = 'zone_handler' AND zone = '$zone' AND theme = '".get_option('template')."'");
	if($position != '') return $position;
		else return 'before';
}

function get_canvas_draggables($zone, $theme = '') {
	if(get_option('canvas_show_zone_name') == 'true' && $zone != 'shelf') echo '<strong>'.$zone.'</strong>';
	if($zone != 'shelf') canvas_show_zone_options($zone, $theme);
	if($theme == '') $theme = get_option('template');
	global $wpdb, $canvas;
	if($wpdb->get_var("SHOW TABLES LIKE '".$canvas->main."'") == $canvas->main)
		$results = $wpdb->get_results("SELECT * FROM ".$canvas->main." WHERE theme = '".$theme."' AND zone LIKE '$zone' ORDER BY position");

    if ($results) {
        foreach($results as $result) {
   			canvas_create_draggable($result->block_id, $zone, $result->position, $result->block_name, '<p>'.$result->description.'</p>', $result->type, $result->block_group);
        }
      }
}

function get_category_id_from_name($name) {
	global $wpdb;
	return $wpdb->get_var("SELECT cat_ID FROM $wpdb->categories WHERE cat_name = '$name'");
}

if(!function_exists('htmlspecialchars_decode')) {
	function htmlspecialchars_decode($str, $quote_style = ENT_COMPAT) {
		return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
	}
}

function is_canvas_ajax() {
	if(strpos($_SERVER["REQUEST_URI"], CANVASURI.'ajax/')) return true;
		else return false;
}

function remove_canvas_node_names($string) {
	return str_replace(array("<canvasnode>","</canvasnode>"), "", $string);
}

?>
